//显示小图片(int)
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>

int lcd_fd;
int *lcd_map = NULL;
char bmpk[6][50] = {"./picture/1.bmp",
"./picture/bbl.bmp",
"./picture/kl.bmp",
"./picture/kq.bmp",
"./picture/qq.bmp",
"./picture/xiaotu.bmp"};

void lcd_open(void)
{
	//打开lcd
	
	lcd_fd = open("/dev/fb0", O_RDWR);
	if(-1 == lcd_fd)
	{
		perror("open lcd failed!\n");
		//return -1;
	}
	lcd_map = mmap(NULL, 800*480*4, PROT_READ|PROT_WRITE, MAP_SHARED, lcd_fd, 0);
	if(NULL == lcd_map)
	{
		perror("mmap failed!\n");
	}
}

int show_bmp(char *picname, int x0, int y0 )
{
	//打开图片
	int bmp_fd;
	bmp_fd = open(picname, O_RDONLY);
	if(-1 == bmp_fd)
	{
		perror("open xiaotu failed!\n");
		return -1;
	}
	
	//利用头54个字节，获得图片的宽和高
	char head[54];
	read(bmp_fd, head, 54);
	int w,h;
	w = *((int *)&head[18]);
	h = *((int *)&head[22]);
	printf("w=%d,h=%d\n",w,h);
	
	int nab,len;
	nab = (4-w*3%4)%4;//需要补齐的字节数
	len = w*3+nab;//补齐后，图片一行的像素字节长度
	
	//偏移54个字节，去掉头信息
	lseek(bmp_fd, 54, SEEK_SET);
	
	//定义图片像素数据缓冲区
	char bmp_buf[len*h*3];
	read(bmp_fd, bmp_buf, sizeof(bmp_buf));
	
	char bmp_bufn[w*h*3];
	for(int j=0;j<h;j++)
	{
		memcpy(&bmp_bufn[j*w*3], &bmp_buf[j*len], w*3);
	}
	//讲24位bmp图片像素转换为32位
	int buf32[w*h];
	int i;
	for(i=0; i<w*h; i++)
	{
		buf32[i] = bmp_bufn[0+i*3]<<0 | bmp_bufn[1+i*3]<<8 | bmp_bufn[2+i*3]<<16 | 0x00<<24;
	}
	
	//翻转图片,将颜色数据写入lcd
	int x,y;
	for(y=0;y<h;y++)
	{
		for(x=0;x<w;x++)
		{
			lcd_map[800*(y0+y)+x0+x] = buf32[w*(h-1-y)+x];
		}
	}
	//关闭bmp
	close(bmp_fd);
}

void allclose(void)
{
	close(lcd_fd);//关闭lcd
	munmap(lcd_map,800*480*4);
}

int main()
{
	lcd_open();
	int n=0;
	while(1)
	{
		show_bmp(bmpk[n++], 0, 0);
		sleep(1);
		if(n>5)
		{
			n=0;
		}
	}
	allclose();
	
	return 0;
}
